/**
 *
 */
package com.ybkj.daijia.server.service.impl;

import com.ybkj.daijia.common.PageVo;
import com.ybkj.daijia.common.Pager;
import com.ybkj.daijia.common.Principal;
import com.ybkj.daijia.server.mapper.DepositRecordMapper;
import com.ybkj.daijia.server.model.DepositRecord;
import com.ybkj.daijia.server.service.DepositRecordService;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class DefaultDepositRecordService implements DepositRecordService {

    @Autowired
    private DepositRecordMapper recordMapper;

    @Override
    public int save(DepositRecord depositRecord) {
        return recordMapper.insertDepositRecord(depositRecord);
    }

    @Override
    public PageVo<DepositRecord> queryAll(Long companyId, String param, Date start, Date end) {

        Map<String, Object> params = new HashMap<String, Object>();
        Subject currentUser = SecurityUtils.getSubject();
        final Principal principal = (Principal) currentUser.getPrincipal();

        PageVo<DepositRecord> vo = new PageVo<DepositRecord>();
        if (companyId != null) {
            params.put("companyId", companyId);
        } else {
            if (!principal.isCompanyType()) {
                params.put("companyId", principal.getCompanyId());
            } else {
                params.put("companyId", null);
            }
        }
        if (StringUtils.isNotBlank(param)) {
            param = "%" + param + "%";
            params.put("param", param);
        }
        if (null != start) {
            params.put("start", start);
        }
        if (null != end) {
            params.put("end", end);
        }
        params.put("offset", Pager.getOffset());
        params.put("size", Pager.getLimit());

        List<DepositRecord> content = recordMapper.selectByPage(params);
        BigDecimal sumMoney = BigDecimal.ZERO;

        sumMoney = recordMapper.sumMoney(params);            //条件查询总押金收入
        BigDecimal sumMoneyRepay = BigDecimal.ZERO;
        sumMoneyRepay = recordMapper.sumMoneyRepay(params);    //条件查询押金退还总额
        BigDecimal sumMoneySurplus = BigDecimal.ZERO;
        sumMoneySurplus = recordMapper.sumMoneySurplus(params);    //条件查询押金剩余总额

        long total = recordMapper.countByPage(params);
        vo.setContent(content);
        vo.setTotalElements(total);
        vo.setSumMoney(sumMoney);
        BigDecimal bigDecimal = BigDecimal.ZERO;
        if (sumMoneyRepay != null) {
            bigDecimal = sumMoneyRepay.multiply(new BigDecimal(-1));
        }
        vo.setSumMoneyRepay(bigDecimal);
        vo.setSumMoneySurplus(sumMoneySurplus);
        return vo;
    }
}